package com.runachina.java;

import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.runachina.common.BaseActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Isay on 2016/1/29.
 */
public class TcpSocket {

    public static WifiManager wifiManager;
    public static WifiManager.MulticastLock lock;// 某些手机接收udp广播需解锁（如HTC）
    public static boolean isConnecting = false;//static才能保持连接
    public static Socket mSocketClient = null;//static才能保持连接
    private static Thread mThreadClient = null;
    private static String recvMessageServer;
    private static String recvMessageClient = "";
    //public static PrintWriter mPrintWriterClient = null;//以字符串形式发送
    //public static BufferedReader mBufferedReaderClient = null;

    private static String ip = "192.168.7.1";//"192.168.0.23";//
    private static int ipport = 25000;//8080

//    private static String ip = "192.168.1.101";//"192.168.0.23";//
//    private static int ipport = 8888;//8080

    public static byte[] recv_byte = new byte[150];//必须定义大小，不然接收不到数据

    // 线程池
    // 为了方便展示,此处直接采用线程池进行线程管理,而没有一个个开线程
    private static ExecutorService mThreadPool;

    /**
     * 发送数据：send_byte
     * 返回   ：是否发送异常
     */
    public static byte[] backOnline_byte;

    public static String wifiSendByte(final byte[] send_byte) {
        String sendResult = "发送成功!";
        backOnline_byte = send_byte;
        if ((isConnecting == true) || (mSocketClient != null)) {
            try {
                //发送数据到服务器的时候，要重新开启一个线程，android 7.0已经修复了这个漏洞
                if (mThreadPool != null) {
                    mThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Log.e("liyuelong", "wifiSendByte: 非心跳包进来的");
                                Log.e("liyuelong", "进来了2");
                                if (mSocketClient != null) {
                                    mSocketClient.getOutputStream().write(send_byte);
                                    mSocketClient.getOutputStream().flush();
                                    Log.e("liyuelong", "发送成功");
                                }
                            } catch (IOException e) {
                                Log.e("liyuelong", "发送失败");
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    mThreadPool = Executors.newCachedThreadPool();
                    try {
                        Log.e("liyuelong", "wifiSendByte: 非心跳包进来的");
                        Log.e("liyuelong", "进来了2");
                        if (mSocketClient != null) {
                            mSocketClient.getOutputStream().write(send_byte);
                            mSocketClient.getOutputStream().flush();
                            Log.e("liyuelong", "发送成功");
                        }
                    } catch (IOException e) {
                        Log.e("liyuelong", "发送失败");
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                sendResult = "发送异常!";
            }
        } else {
            sendResult = "连接断开!";
        }
        return sendResult;
    }

    /**
     * 功能说明：进行socket连接
     * 返回   ：连接结果
     */
    public static String wificonnect() {
        String connecResult = "连接成功!";
        if (wifiManager.isWifiEnabled())// 判断wifi是否开启
        {
            if (wifiManager.getConnectionInfo().getSSID().contains("RU-CL")) {
                if ((isConnecting == false) || (mSocketClient == null))//判断是否没有成功连接设备，或者没有建立socket连接
                {
                /*开始连接*/

                    mThreadClient = new Thread(mRunnable);
                    mThreadClient.start();

                /*等待连接*/
                    BaseActivity.sleep(300);
                /*判断是否连接成功*/
                    if ((isConnecting == false) || (mSocketClient == null)) {
                        connecResult = "连接失败!";
                    }
                } else {
                    Log.e("liyuelong", "wificonnect: " + mSocketClient.getInetAddress().toString());
                    connecResult = "已经连接!";
                }
            } else {
                connecResult = "连接失败!";
            }
        } else {
            connecResult = "wifi未打开!";
        }
        return connecResult;
    }

    public static String readConnect() {
        String connecResult = "连接成功!";
        if (wifiManager.isWifiEnabled())// 判断wifi是否开启
        {
            if ((isConnecting == false) || (mSocketClient == null))//判断是否没有成功连接设备，或者没有建立socket连接
            {
                /*开始连接*/

                /*等待连接*/

                /*判断是否连接成功*/
                if ((isConnecting == false) || (mSocketClient == null)) {
                    connecResult = "连接失败!";
                }
            } else {
                connecResult = "已经连接!";

            }
        } else {
            connecResult = "wifi未打开!";
        }
        return connecResult;
    }

    public static Handler handler = new Handler();
    public static Runnable runnable;
    /**
     * 线程:监听服务器发来的消息
     */
    static Runnable mRunnable = new Runnable() {
        public void run() {
            /*生成完整的ip地址*/
            recvMessageClient = "";
            String ipAddress = new String(ip + ":" + ipport);
            if (ipAddress.length() <= 0) {
                recvMessageClient = "IP不能为空!";
                Message msg = Message.obtain();
                msg.what = 1;
                mHandler.sendMessage(msg);
                return;
            }

            /*简单判断ip地址是否正确*/
            int start = ipAddress.indexOf(":");
            if ((start == -1) || (start + 1 >= ipAddress.length())) {
                recvMessageClient = "IP地址不合法!";
                Message msg = Message.obtain();
                msg.what = 1;
                mHandler.sendMessage(msg);
                return;
            }
            // recv_byte=null;
            /*Socket连接*/
            try {
                mSocketClient = new Socket(ip, ipport);
                if (mSocketClient.isConnected()) {
                    isConnecting = true;
                } else {
                }
                mSocketClient.getInputStream().read(recv_byte);
                mSocketClient.getOutputStream().flush();
                //在scoket连接成功后 开始心跳包任务
                runnable = new Runnable() {
                    public void run() {
                        //每30s发一次心跳包
                        handler.postDelayed(this, 30 * 1000);
                        Log.e("liyuelong", "循环执行心跳包");
                        ClientSender.getClientSender().send(mSocketClient);
                        //postDelayed(this,2000)方法安排一个Runnable对象到主线程队列中
                    }
                };
                handler.postDelayed(runnable, 1000); // 开始Timer
                recvMessageClient = "";//已经连接server!
                Message msg = Message.obtain();
                msg.what = 1;
                mHandler.sendMessage(msg);
            } catch (Exception e) {
                recvMessageClient = "连接IP异常:" + e.toString() + e.getMessage() + "\n";
                Message msg = Message.obtain();
                msg.what = 1;
                mHandler.sendMessage(msg);
                return;
            }

              /*获取数据，存放在recv_data[]中*/
            while (isConnecting) {
                try {
                    Log.e("liyuelong", "进来了3");
                    //每次读取之前先重新new一个对象
                    recv_byte = new byte[150];
                    if (mSocketClient.isConnected()) {
                        Log.e("liyuelong", "进来了4");
                        mSocketClient.getInputStream().read(recv_byte);
                        Log.e("liyuelong", "进来了5");
                    }
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);

                } catch (Exception e) {
                    recvMessageClient = "接收异常!";//"接收异常:" + e.getMessage() + "\n";// 消息换行
                    Message msg = new Message();
                    msg.what = 1;
                    //如果不断开连接，那么程序会一直执行这里，造成程序卡死
                    isConnecting = false;
                    mSocketClient = null;
                    mHandler.sendMessage(msg);
                }
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    };


    public static Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (recv_byte.length > 12) {
                //  BaseActivity.stopTimer();
                for (int i = 0; i < 8; i++) {
                    if ((recv_byte[i] == 0x68) && (recv_byte[i + 1] == recv_byte[i + 3])) {
                        BaseActivity.stopTimer();
                        Log.e("liyuelong", "run: 处理接收到的数据");
                        judgeWhoAnalysis();
                        i = 8;
                    }
                }
                if (recv_byte[0] == 0) {
                    //  stopAnyThing();
                }
            }
        }
    };

    static void judgeWhoAnalysis() {

        switch (BaseActivity.inWhichAc) {
            case "runa.ReadMeterActivity"://runa-读取抄表
                RcvDataAnalysis.runaReadMeterRcv(recv_byte);
                break;
            case "runa.ModifyNumActivity.read"://runa-读取表号
                RcvDataAnalysis.runaModifyMeterReadNumRcv(recv_byte);
                break;
            case "runa.ModifyNumActivity.set"://runa-修改表号
                RcvDataAnalysis.runaModifyMeterSetNumRcv(recv_byte);
                break;
            case "runa.ModifyTimeActivity"://runa-重新对时
                RcvDataAnalysis.runaModifyTimeSetTimeRcv(recv_byte);
                break;
            case "runa.SetAttributeActivity"://runa-仪表属性
                RcvDataAnalysis.SetAttributesetBtn(recv_byte);
                break;
            case "runa.SetDataActivity.read"://runa-数据设置--read
                RcvDataAnalysis.SetDataReadBtn(recv_byte);
                break;
            case "runa.SetDataActivity.set"://runa-数据设置--set
                RcvDataAnalysis.SetDataSetBtn(recv_byte);
                break;
            case "runa.FlowActivity.read"://runa-流量修正-读取
                RcvDataAnalysis.flowRead(recv_byte);
                break;
            case "runa.FlowActivity.set"://runa-流量修正-设置
                RcvDataAnalysis.flowSet(recv_byte);
                break;
            case "runa.CheckActivity"://runa-检定状态-设置
                RcvDataAnalysis.inCheck(recv_byte);
                break;
            case "othercompany.RunaModusActivity"://RunaModus
                RcvDataAnalysis.runamodbus(recv_byte);
                break;
            case "othercompany.OtherCompanyActivity"://OtherCompany
                RcvDataAnalysis.otherCompanyRcv(recv_byte);
                break;
            case "othercompany.EuropeCompanyActivity"://欧标的表
                RcvDataAnalysis.europeCompanyRcv(recv_byte);
                break;
            case "othercompany.HuizhongActivity":// Huizhong
                RcvDataAnalysis.huizhongCompanyRcv(recv_byte);
                break;
            case "common.RudeActivity.readpwr"://Rude读取电量
                RcvDataAnalysis.readPwr(recv_byte);
                break;
            case "common.RudeSimpleActivity.readpwr"://Rude读取电量
                RcvDataAnalysis.readPwrSimple(recv_byte);
                break;
            case "common.RudeRunaModbusActivity.readpwr"://Rude读取电量
                RcvDataAnalysis.readPwrModbus(recv_byte);
                break;
            case "othercompany.RunaModusNumActivity"://Runa_modbus_修改表号
                RcvDataAnalysis.runamodbusNum(recv_byte);
                break;

            /********************************************瑞纳阀门*********************************************/
            case "runavalue.ReadMeterActivity":
                RcvDataAnalysis.runaValveReadMeterRcv(recv_byte);
                break;
            case "runavalue.FactoryResetActivity":
                RcvDataAnalysis.runaValveFactoryResetRcv(recv_byte);
                break;
            case "runavalue.DataResetAvtivity":
                RcvDataAnalysis.runaValveDataResetRcv(recv_byte);
                break;
            case "runavalue.HardwareResetActivity":
                RcvDataAnalysis.runaValveHardwareResetRcv(recv_byte);
                break;
            case "runavalue.ModifyNumActivity.read":
                RcvDataAnalysis.runaValveMofifyReadNumRcv(recv_byte);
                break;
            case "runavalue.ModifyNumActivity.set":
                RcvDataAnalysis.runaValveMofifySetNumRcv(recv_byte);
                break;
            /**********************************************亿林阀门********************************************************/
            case "yilinvalve.YiLinValveReadMeterActivity":
                RcvDataAnalysis.yilinValveReadMeterRcv(recv_byte);
                break;
            /**********************************************瑞纳自主温度采集器***********************************************/
            case "temcollector.TemReadMeterActivity":
                RcvDataAnalysis.runaTemCollReadMeter(recv_byte);//读取表号
                break;
            case "temcollector.TemFactoryResetActivity":
                RcvDataAnalysis.runaTemDataResetRcv(recv_byte,1);//恢复出厂
                break;
            case "temcollector.TemDataResetActivity":
                RcvDataAnalysis.runaTemDataResetRcv(recv_byte,2);//数据清零
                break;
            case "temcollector.TemHardwareResetActivity":
                RcvDataAnalysis.runaTemDataResetRcv(recv_byte,3);//硬件复位
                break;
            case "temcollector.TemModifyNumActivity.read":
                RcvDataAnalysis.runaReadCollModifyMeterNum(recv_byte);//读表号
                break;
            case "temcollector.TemModifyNumActivity.set":
                RcvDataAnalysis.runaSetCollModifyMeterNum(recv_byte);//修改表号
                break;
            default:
                break;
        }
        for (int i = 0; i < recv_byte.length; i++) {
            recv_byte[i] = 0x00;
        }
    }

    /**
     * 关闭心跳
     */
    public static void closeHeart() {
        if (handler != null && runnable != null) {
            Log.e("liyuelong", "closeHeart: 关闭心跳");
            handler.removeCallbacks(runnable);
        }
    }
}
